package com.tr.rentcar.model.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.tr.rentcar.model.GlobalParamHandler;
import com.tr.rentcar.model.bean.UserRecord;
import com.tr.rentcar.model.jdbc.MySqlDb;
import com.tr.rentcar.model.jdbc.ParamHandler;
import com.tr.rentcar.model.jdbc.ResultHandler;


/**
 * 查寻消费记录表
 * @author lenovo
 *
 */
public class UserRecordDao implements ResultHandler<UserRecord>{
	private MySqlDb db = MySqlDb.getInstance();
	/**
	 * 查询所有
	 * @return
	 * @throws SQLException
	 */
	public List<UserRecord> findAll() throws SQLException {
		String sql = "select * from  user_record order by ur_date desc";
		return db.executeQuery(sql,this);
	}
	
	
	/**
	 * 通过用户id查寻(测试)
	 */
	public List<UserRecord> findByid(int uid,int c) throws SQLException {
		StringBuffer sql=new StringBuffer("select * from user_record where uid = "+uid+" order by ur_date desc");
		sql.append(" limit "+c+",13");
		return db.executeQuery(sql.toString(), this);
	}
	/**
	 * 通过用户ID查询记录数
	 */
	public long getAllCount(int uid) throws SQLException{
		String sql="select count(*)as count from user_record where uid=?";
		return (long) db.executeCountQuery(sql,new GlobalParamHandler(uid));
	}
	/**
	 * 添加一条消费记录
	 * @param user
	 * @return
	 * @throws SQLException
	 */
	public boolean save(final UserRecord user) throws SQLException {
		String sql = "insert into user_record(uid,ur_way,ur_money,ur_do_way,ur_name) values(?,?,?,?,?)";
		return db.executeUpdate(sql, new SaveParamHandler(user)) > 0;
	}
	@Override
	public UserRecord doHander(Map<String, Object> row) {
		UserRecord ur= new UserRecord();
		ur.setUrId(Integer.parseInt(row.get("ur_id")+""));
		ur.setuId(Integer.parseInt(row.get("uid")+""));
		ur.setUrWay((String)row.get("ur_way"));
		ur.setUrMoney(Double.valueOf(row.get("ur_money")+""));
		ur.setUrDate((Date) row.get("ur_date"));
		ur.setUrdoWay((String)row.get("ur_do_way"));
		ur.setUrName(row.get("ur_name")+"");
		
		return ur;
	}
	private class SaveParamHandler implements ParamHandler {
		UserRecord user;

		SaveParamHandler(UserRecord user) {
			this.user = user;
		}

		@Override
		public void doHander(PreparedStatement pStatement) throws SQLException {
			// 处理sql参数
			pStatement.setInt(1, user.getuId());
			pStatement.setString(2, user.getUrWay());
			pStatement.setDouble(3, user.getUrMoney());
			pStatement.setString(4, user.getUrdoWay());
			pStatement.setString(5, user.getUrName());
		}
	}
}
